<template>
  <div style="width: 100%; height: 100%">
    <div :id="className" :style="{ height: height, width: width }" />
  </div>
</template>

<script>
  // name: '单独饼形图'
  import * as echarts from 'echarts'

  export default {
    props: {
      // 过滤器
      className: {
        type: String,
        default: 'chart',
      },
      width: {
        type: String,
        default: '100%',
      },
      height: {
        type: String,
        default: '100%',
      },
      barData: {
        // 数据
        type: Array,
        default: Array,
      },
      pieName: {
        type: String,
        default: '统计',
      },
    },
    data() {
      return {
        chart: null,
      }
    },
    // 监听数据变化
    watch: {
      barData: {
        // 监听数据变化
        deep: true,
        handler(val) {
          this.drawPid(val, this.pieName)
        },
      },
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    mounted() {
      this.$nextTick(function () {
        this.drawPid(this.barData, this.pieName)
      })
    },
    methods: {
      drawPid(postData, name) {
        const nameList = []
        const dataList = []
        if (postData.length > 0) {
          postData.forEach(el => {
            nameList.push(el.name)
            dataList.push(el.value)
          })
        }
        const option = {
          title: { text: name },
          xAxis: {
            type: 'category',
            data: nameList, // ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              barWidth: 30,
              data: dataList, // [120, 200, 150, 80, 70, 110, 130],
              type: 'bar',
            },
          ],
        }
        this.chart = echarts.init(document.getElementById(this.className))
        // 使用刚指定的配置项和数据显示图表。
        this.chart.setOption(option)
      },
    },
  }
</script>
